package com.fleet.project01.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.fleet.project01.R;
import com.fleet.project01.adapter.PostAdapter;
import com.fleet.project01.adapter.RepositoryAdapter;
import com.fleet.project01.data.api.RetrofitClient;
import com.fleet.project01.data.model.Post;
import com.fleet.project01.data.model.Repository;
import com.fleet.project01.utils.LogUtils;
import com.fleet.project01.utils.NetworkUtils;
import com.fleet.project01.utils.ToastUtils;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    
    private EditText etName;
    private Button btnSubmit;
    private TextView tvLoading;
    private LinearLayout loadingLayout;
    private RecyclerView recyclerView;
    private RepositoryAdapter repositoryAdapter;
    private PostAdapter postAdapter;
    
    // 当前显示模式：true为Repository模式，false为Post模式
    private boolean isRepositoryMode = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        initViews();
        setupRecyclerView();
        setupClickListeners();

        // 页面加载时自动搜索默认用户
        autoSearchDefaultUser();
    }

    private void initViews() {
        etName = findViewById(R.id.etName);
        btnSubmit = findViewById(R.id.btnSubmit);
        tvLoading = findViewById(R.id.tvLoading);
        loadingLayout = findViewById(R.id.loadingLayout);
        recyclerView = findViewById(R.id.recyclerView);
    }

    private void setupRecyclerView() {
        // 初始化两个适配器
        repositoryAdapter = new RepositoryAdapter();
        postAdapter = new PostAdapter();
        
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        
        // 默认使用Post适配器
        recyclerView.setAdapter(postAdapter);
        
        // 设置Repository列表项点击事件
        repositoryAdapter.setOnItemClickListener(repository -> {
            ToastUtils.showShort("点击了仓库: " + repository.getName());
            LogUtils.d("点击了仓库: " + repository.getName() + ", URL: " + repository.getHtmlUrl());
        });
        
        // 设置Post列表项点击事件
        postAdapter.setOnItemClickListener(post -> {
            ToastUtils.showShort("点击了文章: " + post.getTitle());
            LogUtils.d("点击了文章ID: " + post.getId() + ", 标题: " + post.getTitle());
        });
    }

    private void setupClickListeners() {
        btnSubmit.setOnClickListener(v -> {
            String input = etName.getText().toString().trim();
            if (TextUtils.isEmpty(input)) {
                ToastUtils.showShort("请输入内容");
                return;
            }
            LogUtils.d("页面加载，自动搜索所有文章");
            searchAllPosts();
        });
    }

    /**
     * 页面加载时自动搜索默认数据
     */
    private void autoSearchDefaultUser() {
        searchAllPosts();
    }

    /**
     * 判断字符串是否为数字
     */
    private boolean isNumeric(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    private void searchUserRepositories(String username) {
        // 检查网络连接
        if (!NetworkUtils.isNetworkConnected()) {
            ToastUtils.showShort("网络连接不可用，请检查网络设置");
            return;
        }

        showLoading(true);
        LogUtils.d("开始搜索用户: " + username + " 的仓库");

        Call<List<Repository>> call = RetrofitClient.getApiService().getUserRepos(username);
        call.enqueue(new Callback<List<Repository>>() {
            @Override
            public void onResponse(Call<List<Repository>> call, Response<List<Repository>> response) {
                showLoading(false);
                
                if (response.isSuccessful()) {
                    List<Repository> repositories = response.body();
                    if (repositories != null && !repositories.isEmpty()) {
                        LogUtils.d("获取到 " + repositories.size() + " 个仓库");
                        switchToRepositoryMode();
                        repositoryAdapter.setRepositories(repositories);
                        ToastUtils.showShort("找到 " + repositories.size() + " 个仓库");
                    } else {
                        LogUtils.d("该用户没有公开仓库");
                        switchToRepositoryMode();
                        repositoryAdapter.setRepositories(null);
                        ToastUtils.showShort("该用户没有公开仓库");
                    }
                } else {
                    LogUtils.e("请求失败: " + response.code() + " - " + response.message());
                    switchToRepositoryMode();
                    repositoryAdapter.setRepositories(null);
                    if (response.code() == 404) {
                        ToastUtils.showShort("用户不存在");
                    } else {
                        ToastUtils.showShort("请求失败，请稍后重试");
                    }
                }
            }

            @Override
            public void onFailure(Call<List<Repository>> call, Throwable t) {
                showLoading(false);
                LogUtils.e("网络请求失败: " + t.getMessage());
                repositoryAdapter.setRepositories(null);
                ToastUtils.showShort("网络请求失败，请检查网络连接");
            }
        });
    }

    /**
     * 搜索所有文章
     */
    private void searchAllPosts() {
        // 检查网络连接
        if (!NetworkUtils.isNetworkConnected()) {
            ToastUtils.showShort("网络连接不可用，请检查网络设置");
            return;
        }

        showLoading(true);
        LogUtils.d("开始搜索所有文章");

        Call<List<Post>> call = RetrofitClient.getApiService().getAllPosts();
        call.enqueue(new Callback<List<Post>>() {
            @Override
            public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
                showLoading(false);
                
                if (response.isSuccessful()) {
                    List<Post> posts = response.body();
                    if (posts != null && !posts.isEmpty()) {
                        LogUtils.d("获取到 " + posts.size() + " 篇文章");
                        switchToPostMode();
                        postAdapter.setPosts(posts);
                        ToastUtils.showShort("找到 " + posts.size() + " 篇文章");
                    } else {
                        LogUtils.d("没有找到文章");
                        switchToPostMode();
                        postAdapter.setPosts(null);
                        ToastUtils.showShort("没有找到文章");
                    }
                } else {
                    LogUtils.e("请求失败: " + response.code() + " - " + response.message());
                    switchToPostMode();
                    postAdapter.setPosts(null);
                    ToastUtils.showShort("请求失败，请稍后重试");
                }
            }

            @Override
            public void onFailure(Call<List<Post>> call, Throwable t) {
                showLoading(false);
                LogUtils.e("网络请求失败: " + t.getMessage());
                switchToPostMode();
                postAdapter.setPosts(null);
                ToastUtils.showShort("网络请求失败，请检查网络连接");
            }
        });
    }

    /**
     * 切换到Post显示模式
     */
    private void switchToPostMode() {
        if (isRepositoryMode) { // 如果当前是Repository模式，才需要切换
            isRepositoryMode = false;
            recyclerView.setAdapter(postAdapter);
            LogUtils.d("切换到Post显示模式");
        }
    }

    /**
     * 切换到Repository显示模式
     */
    private void switchToRepositoryMode() {
        if (!isRepositoryMode) { // 如果当前是Post模式，才需要切换
            isRepositoryMode = true;
            recyclerView.setAdapter(repositoryAdapter);
            LogUtils.d("切换到Repository显示模式");
        }
    }

    private void showLoading(boolean isLoading) {
        if (isLoading) {
            loadingLayout.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            btnSubmit.setEnabled(false);
            btnSubmit.setText("搜索中...");
        } else {
            loadingLayout.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            btnSubmit.setEnabled(true);
            btnSubmit.setText("搜索");
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            ToastUtils.showShort("设置功能待开发");
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}